import React from 'react';
import { Spin } from 'antd';
import * as ReactDOM from 'react-dom';

/**
 * @example
 * import Loading  from '@/components/Loading';
 * const loading = new Loading()
 * loading.open()  打开
 * loading.close() 关闭
 * loading.destroy 销毁
 * @description open 和 close 要同时使用，否则会出现未关闭的情况
 */

class Loading {
  static install: Loading;
  public div: HTMLDivElement | null;
  public requestCount:number
  readonly classNameShow: string;
  readonly classNameHide: string;
  readonly classNameShowHideMask: string;
  constructor() {
    this.div = null;
    this.classNameShow = 'my-loading_show';
    this.classNameHide = 'my-loading_hide';
    this.classNameShowHideMask = 'my-loading_show-hide-mask';
    this.requestCount = 0;

    if (Loading.install) {
      return Loading.install;
    }

    this.render();

    Loading.install = this;
  }
  private render() {
    const div = document.createElement('div');
    document.body.appendChild(div);
    div.className = this.classNameHide;
    this.div = div;
    setTimeout(() => {
      ReactDOM.render(
        <Spin size="large" />,
        div,
      );
    });
  }

  private isShowMask() {
    const pathName = window.location.pathname;
    const reg = new RegExp(/defalut$/gi); // 选座页面不显示loading的蒙版
    return !reg.test(pathName);
  }

  public destroy() {
    if (!this.div) return;
    const unmountResult = ReactDOM.unmountComponentAtNode(this.div);
    if (unmountResult && this.div.parentNode) {
      this.div.parentNode.removeChild(this.div);
    }
    this.div = null;
  }

  public open() {
    this.requestCount++;
    if (!this.div) {
      this.render();
    } else if (this.div.className === this.classNameHide) {
      this.div.className = this.isShowMask()
        ? this.classNameShow
        : this.classNameShowHideMask;
    }
  }

  public close() {
    this.requestCount--;
    if (
      this.requestCount <= 0 &&
      this.div &&
      (this.div.className === this.classNameShow ||
        this.div.className === this.classNameShowHideMask)
    ) {
      this.requestCount = 0;
      this.div.className = this.classNameHide;
    }
  }
}

export default Loading;
